<?php

namespace Api\Openapi;

use S\Http;

/**
 * Class Notify
 * @package Api\Openapi
 * @description 通知服务, 发送通知给应用方, 通知服务会自动重试,直到成功或者超过限制次数
 *
 * 以下为使用样例：
 *
 * //提交一条通知
 * $ret = \Api\Openapi\Notify::submit(
 *   'Ls7fN4Aiw5iey',
 *   'http://loans.hrbbwx.com/api/test/callback',
 *   '{"Content-Type":"application/json"}',
 *   '{"id":"Ls7fN4Aiw5iey","success_time":"2016-05-10 10:00:00"}',
 *   'POST',
 *   3000,
 *   '/^success$/'
 * );
 *
 *
 */
class Notify extends Util {

    const SUBMIT_URL = '/notify/submit';

    const LOG_URL = '/notify/query/log';
    const INFO_URL = '/notify/query/info';

    /**
     *  提交一条通知
     * @param string $msg_id
     * @param string $url
     * @param string $request_header json
     * @param string $request_body json
     * @param string $method
     * @param int $timeout  //默认3000 ms
     * @param string $succ_rule // 可为空,默认校验返回{success:true} or {success:"true"} 为成功
     * @return boolean
     * @throws \S\Exception
     */
    public static function submit($msg_id, $url, $request_header, $request_body, $method, $timeout = 3000, $succ_rule = '') {
        $data = array(
            'msg_id' => $msg_id,
            'url' => $url,
            'request_header' => $request_header,
            'request_body' => $request_body,
            'method' => $method,
            'timeout' => $timeout,
            'succ_rule' => $succ_rule
        );

        self::request(self::SUBMIT_URL, array(
            'header' => array(),
            'body' => $data
        ));
        return true;
    }

    /**
     * 查询到数据最后一条数据
     * @param string $msg_id
     * @return array
     * @throws \S\Exception
     * @example
     *    正常返回数据格式为
     *         array (
     *           'msg_id' => '1234227209','appkey' => 'URpaJQHdXErc',
     *           'num' => 4,'ctime' => '2016-05-17 20:44:36','method' => 'POST',
     *           'request_body' => array ('name' => 'cyc',),
     *           'request_header' => array ( ),
     *           'status' => 0, 'succ_rule' => '', 'timeout' => 3000,
     *           'url' => 'http://test.hrbbwx.dev/api/test/callback',
     *          ),
     *
     */
    public static function getInfo($msg_id) {
        $data = array(
            'msg_id' => $msg_id
        );

        $ret = self::request(self::INFO_URL, array(
                'header' => array(),
                'body' => $data,
            )
        );
        return !empty($ret['data']) ? $ret['data'] : array();
    }

    /**
     * 根据msg_id查询所有的记录
     * @param string $msg_id
     * @return array
     */
    public static function getLog($msg_id) {
        $data = array(
            'msg_id' => $msg_id
        );
        $ret = self::request(self::LOG_URL, array(
            'header' => array(),
            'body' => $data
        ));

        return !empty($ret['data']) ? $ret['data'] : array();
    }
}